import { getLocalHistories } from '@/utils/storage';

const initialState = { suggestList: [] as string[], historyList: getLocalHistories(), resultData: {} as ResultData };

export default function searchReducer(state = initialState, action: any) {
  switch (action.type) {
    case 'search/setSearch':
      return { ...state, suggestList: action.payload.filter((item: string) => !!item) };
    case 'search/clearSearch':
      return { ...state, suggestList: action.payload };
    case 'search/setHistory':
      return {
        ...state,
        historyList: action.payload,
      };
    case 'search/clearHistory':
      return {
        ...state,
        historyList: action.payload,
      };
    case 'search/setSearchResult':
      return {
        ...state,
        //数据合并
        resultData: {
          ...action.payload,
          //旧数据和新数据的results进行合并 旧数据的results是一个数组 新数据的results也是一个数组 所以要用扩展运算符 ... 将两个数组合并
          results: [...(state.resultData.results || []), ...action.payload.results],
        },
      };
    case 'search/clearSearchResult':
      return {
        ...state,
        resultData: action.payload,
      };
    default:
      return state;
  }
}

interface ResultData {
  page: number;
  per_page: number;
  results: Result[];
  total_count: number;
}

export interface Result {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: Cover;
  like_count: number;
  collect_count: number;
}

interface Cover {
  type: number;
  images?: string[];
}
